using FluentValidation;
using FluentValidationExample.Application.Customers.Commands;
using FluentValidationExample.Application.Customers.Contracts;
using FluentValidationExample.Filters;
using FluentValidationExample.Middlewares;
using FluentValidationExample.Validations;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });

// 是否禁止内置模型验证
if (false)
{
    builder.Services.AddSingleton<IObjectModelValidator, TestObjectModelValidator>(serviceProvider =>
        new TestObjectModelValidator(
            serviceProvider.GetRequiredService<IModelMetadataProvider>(),
            serviceProvider.GetRequiredService<IOptions<MvcOptions>>().Value.ModelValidatorProviders,
            true));
}


builder.Services.AddControllers(options =>
{
    // 在验证错误中使用 JSON 属性名称
    // options.ModelMetadataDetailsProviders.Add(new SystemTextJsonValidationMetadataProvider());
    // options.Filters.Add<FluentValidationAutoValidationActionFilter>();

    options.Filters.Add(new ModelValidationFilter());
    options.Filters.Add(new ModelValidationFilter1());
});


builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(typeof(CreateCommand).Assembly));
builder.Services.AddValidatorsFromAssembly(typeof(CreateCommandValidation).Assembly);

// builder.Services.AddSingleton<IProblemDetailsService, ProblemDetailsService>();
builder.Services.AddProblemDetails();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseMiddleware<GlobalExceptionHandlerMiddleware>();

app.MapPost("/Create", async (CreateCustomerRequest createRequest, IMediator mediator) =>
    {
        await mediator.Send(new CreateCommand(Guid.NewGuid(), createRequest.Name, createRequest.Code));

        return TypedResults.Ok();
    })
    .WithTags("Customers");

app.MapControllers();
app.Run();